<?php
declare (strict_types = 1);

namespace app\validate\common\user;

use app\model\communal\UserExpertModel;
use app\model\communal\UserModel;
use think\Validate;

class ExpertValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id' => ['require', 'number', 'gt:0'],
        'name' => ['require', 'max:100'],
        'gender' => ['in:1,2'],
        'mobile' => ['require', 'mobile'],
        'is_interpreter' => ['require', 'in:1,2'],

        /*
         * 培训情况
         */
        'training' => [],

        'state' => ['in:1,2'],
        'page' => ['number', 'gt:0'],
        'page_size' => ['number', 'gt:0'],
    ];

    protected $field = [
        'name' => '姓名',
        'gender' => '性别',
        'mobile' => '手机号码',
        'is_interpreter' => '量表解读师',

        /*
         * 培训情况
         */
        'training' => '培训情况',

        'page' => '当前页数',
        'page_size' => '每页条数',
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [
    ];

    /**
     * 场景
     * @var array
     */
    protected $scene = [
        'index' => ['page', 'page_size'],
        'read' => ['id'],
    ];

    /**
     * scene save owner
     *
     * @return $this
     */
    public function sceneSave()
    {
        return $this->only(UserExpertModel::$saveColumn)
            ->append('mobile', 'checkMobileUnique:save');
    }

    /**
     * scene update
     *
     * @return $this
     */
    public function sceneUpdate()
    {
        return $this->only(UserExpertModel::$updateColumn)
            ->append('mobile', 'checkMobileUnique:update');
    }

    /**
     * scene item
     *
     * @return $this
     */
    public function sceneItem()
    {
        return $this->only(['id', 'name', 'state']);
    }

    /**
     * 唯一验证
     *
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|mixed
     */
    protected function checkMobileUnique($value, $rule, $data)
    {
        $data['delete_at'] = 0;
        if ('save' === $rule) {
            $check = $this->unique($value, UserExpertModel::class . ',mobile^delete_at', $data, 'mobile^delete_at');
        } else {
            $check = $this->unique($value,UserExpertModel::class . ',mobile^delete_at,' . $data['id'], $data, 'mobile^delete_at');
        }

        if (true !== $check) {
            return lang(':attribute has exists');
        }

        return true;
    }
}
